﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;

namespace Smith.ImageConverter
{
    public class ConverterTask
    {
        protected bool delSrc;
        protected string destDir;
        protected IConvert converte;
        protected IResize resize;        
        protected IRename rename;
        protected IRotation rotation;
        protected object clock = new object();
        protected object slock = new object();

        public ConverterTask()
        {
        }

        public ConverterTask(string[] files)
        {
            Files = files;
        }

        public string[] Files { get; protected set; }

        public List<TaskItem> TaskList { get; protected set; }

        public int TotalCount { get; protected set; }

        public string OutputDirectory { get; protected set; }

        public void InitializeTask()
        {
            TotalCount = Files.Length;
            delSrc = Provider.IsDeleteSource();
            destDir = Provider.GetDefaultOutputDirectory();            
            converte = Provider.GetDefaultConvert();
            resize = Provider.GetDefaultResize();
            rename = Provider.GetDefaultRename();
            rotation = Provider.GetDefaultRotation();
            InitializeTaskList();
        }

        public void ProcessAll()
        {
            foreach (var item in TaskList) Process(item);
        }

        public void Process(TaskItem item)
        {
            //if (item.Source == item.Target) return;
            try
            {
                Bitmap img = new Bitmap(item.Source);
                Bitmap res_1 = resize.Resize(img);                
                Bitmap rot_1 = rotation.Rotate(res_1);
                rot_1.Tag = img.RawFormat;
                img.Dispose();
                converte.Save(rot_1, item.Target);
                rot_1.Dispose();
                res_1.Dispose();                
            }
            catch (Exception) { }
            finally
            {
                if (item.Source != item.Target && delSrc) AppHelper.DeleteFile(item.Source);
            }
        }

        protected void InitializeTaskList()
        {
            TaskList = new List<TaskItem>();
            foreach (var item in Files)
            {
                TaskList.Add(
                    new TaskItem
                    {
                        Target = rename.GetNewName(item, destDir),
                        Source = item
                    });
            }            
        }
    }

    public class TaskItem
    {
        public string Source { get; set; }
        public string Target { get; set; }
    }
}
